﻿using King.Box.CacheProvider;
using King.Box.Models.Db.Basic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace King.Box.Service.Impl
{
    public class BasicService : IBasicService
    {
        private readonly IDataService<Basic_Dictionary> _dicDataProvider;

        public BasicService(IDataService<Basic_Dictionary> dicDataProvider)
        {
            _dicDataProvider = dicDataProvider;
        }

        #region BasicConfig
        public string GetDictionaryValue(string flag)
        {
            var dic = this.GetDictionary(flag);
            if (dic == null)
                return string.Empty;

            return dic.Value;
        }

        public T  GetDictionaryValue<T>(string flag)
        {
            var dic = this.GetDictionary(flag);
            if (dic == null)
                return default(T);

            return (T)Convert.ChangeType(dic.Value, typeof(T));
        }
        #endregion

        #region Dictionary
        public Basic_Dictionary GetDictionary(string flag)
        {
            if (MemoryCacheProvider.Instance.Exists(flag))
                return MemoryCacheProvider.Instance.Get<Basic_Dictionary>(flag);

            var dic = _dicDataProvider.Get(x => x.Flag.Equals(flag));
            if (dic != null)
            {
                MemoryCacheProvider.Instance.Add(dic.Flag, dic);
                return dic;
            }

            return null;
        }
        #endregion
    }
}
